﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;

public partial class RegisSale : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            Session["CurrentPage"] = "RegisSale.aspx";

            if (!CheckLogin()) Response.Redirect("login.aspx");
            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            string type = Request["type"] ?? "default";

            switch (type)
            {
                case "default":
                    {
                        LoadFile("regissale.html", false);
                        LoadRegisSale();
                        break;
                    }
                case "add":
                    {
                        LoadFile("news_add.html", false);
                        LoadNewsByID(null);
                        break;
                    }
                case "edit":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("RegisSale.aspx");
                        }
                        else
                        {
                            LoadFile("news_add.html", false);
                            LoadNewsByID(long.Parse(Request["id"]));
                        }
                        break;
                    }
                case "delete":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("RegisSale.aspx");
                        }
                        else
                        {
                            DeleteRegisSaleByID(long.Parse(Request["id"]));
                            Response.Redirect("RegisSale.aspx");
                        }
                        break;
                    }
                default: goto case "default";
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadRegisSale()
    {
        try
        {
            var regissale = _DR.Meta.Where(m => m.LanguageCode.Equals(_currentLanguage) && m.Type.Equals("RegisSale")).OrderByDescending(m => m.ID).Select(m => new { ID = m.ID, Email = m.Key }).ToList();


            string search = Request["search"] ?? string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                regissale = regissale.Where(n => n.Email.ToLower().Contains(search.ToLower())).ToList();
                _parser.Assign("searchValue", search);
            }

            double totalRecord = regissale.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("regissaleID", regissale[i].ID.ToString());
                    _parser.Assign("regissaleTitle", regissale[i].Email);

                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }

            _parser.Parse("Main.Content");

            regissale = null;
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadNewsByID(long? ID)
    {
        try
        {
            List<SelectCategory> selectCategory = (from term in _DR.Terms
                                                   join taxonomy
                                                       in _DR.Taxonomy on term.ID equals taxonomy.Term
                                                   where taxonomy.Name.Equals("news-category") && taxonomy.LanguageCode.Equals(_currentLanguage)
                                                   select new SelectCategory()
                                                   {
                                                       ID = term.ID,
                                                       Name = term.Name,
                                                       Parent = taxonomy.Parent
                                                   }).ToList();

            BuildSelectCategory = (ParentId, Level) =>
            {
                return (from c in selectCategory
                        where c.Parent == ParentId
                        from t in new List<SelectCategory>()
                        {
                            new SelectCategory()
                            {
                                ID = c.ID,
                                Name = new String('-', Level).Replace("-", "&mdash;") + c.Name,
                                Parent = c.Parent
                            }
                        }.Union(BuildSelectCategory(c.ID, Level + 1))
                        select t).ToList();
            };

            selectCategory = BuildSelectCategory(0, 0);

            foreach (SelectCategory s in selectCategory)
            {
                _parser.Assign("categoryID", s.ID.ToString());
                _parser.Assign("categoryName", s.Name.Replace("&mdash;", ""));
                _parser.Assign("position", s.Name.IndexOf("&mdash;") == -1 ? string.Empty : " style=\"padding-left:" + (s.Name.LastIndexOf("&mdash;") == 0 ? 1 : s.Name.LastIndexOf("&mdash;") / 7 + 1) + "em!important\"");
                _parser.Parse("Main.Content.EditForm.Category.CategoryItem");
            }

            if (selectCategory.Count != 0) _parser.Parse("Main.Content.EditForm.Category");

            if (ID == null) //AddNew
            {
                _parser.Assign("newsTitle", string.Empty);
                _parser.Assign("newsDate", string.Empty);
                _parser.Assign("newsExcerpt", string.Empty);
                _parser.Assign("newsHot", string.Empty);
                _parser.Assign("newsImage", string.Empty);
                _parser.Assign("newsImageThumbnail", string.Empty);
                _parser.Assign("newsOrder", string.Empty);
                _parser.Assign("newsContent", string.Empty);

                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
                _parser.Parse("Main.AddNewNews");
            }
            else //Edit
            {
                Posts news = _DR.Posts.Where(t => t.ID.Equals(ID.Value)).FirstOrDefault();

                if (news == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    long[] longCategories = _DR.Relations.Where(r => r.Type.Equals("news-category") && r.Child.Equals(ID.Value)).Select(r => r.Parent).ToArray();
                    string[] stringCategories = Array.ConvertAll<long, string>(longCategories, delegate(long number) { return number.ToString(); });

                    List<Meta> metas = _DR.Meta.Where(m => m.Object.Equals(ID.Value) && m.Type.Equals("news")).ToList();

                    string hotNews = (metas.Where(m => m.Key.Equals("NewsHot")).Select(m => m.Value).FirstOrDefault() ?? string.Empty) == "True" ? "checked=\"checked\"" : string.Empty;

                    _parser.Assign("selectedCategory", string.Join(",", stringCategories));

                    _parser.Assign("newsID", news.ID.ToString());
                    _parser.Assign("newsTitle", news.Title);
                    _parser.Assign("newsExcerpt", news.Excerpt);
                    _parser.Assign("newsHot", hotNews);
                    _parser.Assign("newsImage", metas.Where(i => i.Key.Equals("NewsImage")).Select(i => i.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("newsImageThumbnail", metas.Where(i => i.Key.Equals("NewsImageThumbnail")).Select(i => i.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("newsDate", news.Date.ToShortDateString());
                    _parser.Assign("newsOrder", news.Order.ToString());

                    _parser.Assign("newsContent", news.Content);
                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.EditNews");

                    longCategories = null;
                    stringCategories = null;
                }

                news = null;
                selectCategory = null;
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteRegisSaleByID(long ID)
    {
        try
        {
            Meta regissale = _DR.Meta.Where(t => t.ID.Equals(ID)).FirstOrDefault();

            if (regissale != null)
            {
                _DR.DeleteObject(regissale);
                _DR.SaveChanges();
            }

            regissale = null;
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}